from flask import render_template, session, current_app, g, abort, jsonify, request

from info import constants, db
from info.models import User, News, Comment, CommentLike

from info.modules.news import news_blu
from info.utils.common import user_login
from info.utils.response_code import RET

#添加 评论

@news_blu.route("/news_comment",methods=["POST"])
@user_login
def news_comment():

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    news_id = request.json.get("news_id")
    comment_str = request.json.get("comment")
    parent_id = request.json.get("parent_id")

    if not all([news_id, comment_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数类型错误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not news:

        return jsonify(errno=RET.NODATA, errmsg="该条新闻不存在")
    #添加新闻评论

    comment = Comment()
    comment.news_id = news_id
    comment.user_id = user.id
    comment.content = comment_str
    if parent_id:
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

#点赞
@news_blu.route("/comment_like",methods=["POST"])
@user_login
def set_comment_like():
    user =g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    comment_id = request.json.get("comment_id")
    action = request.json.get('action')

    if not all([comment_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    if action not in["add","remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        comment_id =int(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        comment_obj = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not comment_obj:
        return jsonify(errno=RET.NODATA, errmsg="该评论不存在")
    comment_like_obj = CommentLike.query.filter_by(comment_id=comment_id, user_id=user.id).first()

    if action == "add":
        if not comment_like_obj:
            comment_like =CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = user.id
            db.session.add(comment_like)
            comment_obj.like_count += 1
    else:
        if comment_like_obj:
            db.session.delete(comment_like_obj)
            comment_obj.like_count -= 1

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")
    return jsonify(errno=RET.OK,errmsg='OK')
@news_blu.route("/news_collect",methods =["POST"])
@user_login
def news_collect():


    user = g.user

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    news_id = request.json.get("news_id")
    action = request.json.get("action")

    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="数据格式不正确")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="该条新闻不存在")


    #业务逻辑 点击收藏 先判断是否 已收藏,if 收藏 -添加. else 删除
    if action == "collect":
        if news not in user.collection_news:
            user.collection_news.append(news)
        else:

            if news in user.collection_news:
                user.collection_news.remove(news)

    return jsonify(errno=RET.OK, errmsg="OK")

@news_blu.route("/<int:news_id>")
@user_login
def detail(news_id):
    user = g.user
    clicks_news =[]

    try:
        clicks_news = News.query.order_by(News.clicks.desc()).limit(
            constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)

    clicks_news_li = [news.to_basic_dict() for news in clicks_news]
    news = None
    try:
        news= News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not news:
        abort(404)

    news.clicks +=1

    is_collected =False

    if user and news in user.collection_news.all():
        is_collected =True

    comments =[]
    try:
        comments= Comment.query.filter(Comment.news_id==news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    comments_dict_li = []
    for comment in comments:
        comment_dict = comment.to_dict()
        comment_dict['is_like'] = False
        if  user and CommentLike.query.filter(CommentLike.comment_id ==comment.id, CommentLike.user_id== user.id).first():
            comment_dict["is_like"] = True

        comments_dict_li.append(comment_dict)




    data = {
        "user_info": user.to_dict() if user else None,
        "clicks_news_li": clicks_news_li,
        "news": news.to_dict(),
        "is_collected": is_collected,
        "comments_dict_li": comments_dict_li

        }
    return render_template("news/detail.html", data=data)